/**
 * @author train
 */

import React, { Component } from 'react'
import {
  View,
  Text,
  Easing,
  Animated,
  Platform,
  StyleSheet,
  Dimensions,
  ScrollView,
  TouchableWithoutFeedback,
  TouchableOpacity,
} from 'react-native'

import { px2dp } from '../utils'

const { width, height } = Dimensions.get('window')

export default class TabBar extends Component {
  constructor(props) {
    super(props)
    this.state = {
      activeIndex: 0,
      left: new Animated.Value(0),
    }
    this.tabWidth = props.containerWidth / props.tabs.length
  }
  onTabChange(index, item) {
    const { init } = this.props
    this.setState({
      activeIndex: index,
    })
    let duration = 250
    if (init) {
      duration = 0
    }
    Animated.timing(this.state.left, {
      toValue: this.tabWidth * index,
      duration,
    }).start()
    this.props.onTabChange(index, item)
  }
  renderItem() {
    const { tabs } = this.props
    return tabs.map((item, index) => {
      let color = '#444'
      if (index == this.state.activeIndex) {
        color = '#e23f3c'
      }
      return (
        <TouchableOpacity
          key={index}
          style={{ flex: 1 }}
          onPress={() => {
            this.onTabChange(index, item)
          }}
        >
          <View style={styles.item}>
            <Text style={{ color }}>{item.label}</Text>
          </View>
        </TouchableOpacity>
      )
    })
  }
  componentDidMount() {
    const activeIndex = this.props.activeIndex || 0
    const { tabs } = this.props
    this.onTabChange(activeIndex, tabs[activeIndex])
  }
  render() {
    const tabUnderlineStyle = {
      position: 'absolute',
      width: this.tabWidth,
      bottom: 0,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: 'transparent',
    }

    return (
      <View style={styles.container}>
        {this.renderItem()}
        <Animated.View style={[tabUnderlineStyle, { left: this.state.left }]}>
          <View style={{ height: 2, width: 40, backgroundColor: '#e23f3c' }} />
        </Animated.View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    height: 36,
    flexDirection: 'row',
    backgroundColor: 'white',
  },
  item: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
})
